// index.js
// 获取应用实例
import {
  post,
  get,
  put
} from '../../utils/request'
import {
  APIS
} from '../../utils/api';
import {
  systemList
} from '../../utils/system';
import {
  setVoiceSystem,
  setBallSystem,
  stageList
} from '../../utils/util';
const app = getApp();

Page({
  data: {
    currentShop: '',
    currentShopName: '',
    info: {},
    userInfo: {},
    type: '',
    coupon: '',
    // 是否为小程序内进入
    inner: 0,
    id: '',
    isShowScan: false,
    isShowTip: false,
    isShowHyTip: false,
    isShowDy: true,
    stageList: [{
      id: 1,
      name: '会员开台',
      desc: '会员余额大于押金直接开台',
      used: true
    },
    {
      id: 2,
      name: '自助开台',
      desc: '押金开台，结束后自动退回',
      used: true
    },
    {
      id: 3,
      name: '抖音团购开台',
      desc: '订单二维码截图扫码开台',
      used: true
    },
    {
      id: 4,
      name: '美团/点评开台',
      desc: '添加店长微信兑换开台',
      used: true
    },
    {
      id: 5,
      name: '定时开台',
      desc: '设定开台时长，打球免押金',
      used: true
    }
    ],
    currentZz: {
      id: 2,
      used: true
    },
    currentDy: {
      id: 3,
      used: true
    },
    customMessage: '',
    customPath: ''
  },
  onShareAppMessage: function () {
    // 自定义分享内容
    const { id, type } = this.data;
    console.log(`/subPackage/pages/stage?id=${id}&type=${type}`,44);
    return {
      title: '',
      path: `/subPackage/pages/stage?id=${id}&type=${type}`, // 可以在路径中添加参数
      imageUrl: ''
    };
  },
  onLoad(options) {
    // 初始化数据，例如从options获取参数等。
    this.setData({
      customMessage: options.message || '',
      customPath: options.path || '/pages/index/index'
    });

    const currentShopName = wx.getStorageSync('currentShopName');
    const currentShop = wx.getStorageSync('currentShop');
    const {
      type,
      id,
      coupon,
      inner
    } = options;
    this.setData({
      id,
      type,
      coupon,
      currentShopName,
      currentShop,
      inner
    });
    this.getInfo(type, id);
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res);
      }
    })
    const h = new Date().getHours();
    this.setData({
      isShowDy: h > 2 && h < 10
    });
  },
  getInfo(type, id) {
    const userInfo = wx.getStorageSync('userInfo');
    console.log('userInfo', userInfo);
    // 判断用户是否已登录
    if (!userInfo) {
      wx.navigateTo({
        url: '/subPackage/pages/login'
      })
      return;
    }
    const url = type === 'ball' ? APIS.ball : APIS.card;
    get(`${url}/${id}`).then(res => {
      const info = res.data;
      this.setData({
        info: {
          ...info,
          currFee: parseInt(info.currFee)
        },
        userInfo
      });
      this.changeStageListStatus(info);
    });
  },
  handleJumpToShop() {
    wx.switchTab({
      url: '/pages/shop/index'
    })
  },
  handleJumpToMd() {
    this.setData({
      isShowTip: true
    });
  },
  handleClose() {
    this.setData({
      isShowTip: false
    });
  },
  handleCloseHy() {
    this.setData({
      isShowHyTip: false
    });
  },
  handleScan() {
    const that = this;
    const { type } = this.data;
    wx.scanCode({
      async success(res) {
        const url = res.result;
        console.log(url);

        that.getNuclear(url, type);
      }
    })
  },
  handleCloseScan() {
    this.setData({
      isShowScan: false
    });
  },
  changeStageListStatus(info) {
    const stageList = this.data.stageList;
    const result = stageList.map((x, i) => {
      if (i === 0) {
        return {
          ...x,
          used: Number(this.data.userInfo.amount) > Number(info.deposit)
        }
      } else if (i === 1) {
        return {
          ...x,
          // used: info.deposit > 0
          used: true
        }
      } else {
        return x;
      }
    });
    this.setData({
      stageList: result
    })
  },
  async handleTask(e) {
    const {
      item
    } = e.target.dataset;
    const {
      id,
      used
    } = item;
    if (id === 1) {
      if (!used && id === 1) {
        this.setData({
          isShowHyTip: true
        });
      }
      // 用户状态
      let status = await get(APIS.user + '/status', {
        luid: this.data.userInfo.id
      })
      console.log(status, '=======')
      if (status.code !== 0) {
        wx.showToast({
          icon: 'none',
          title: status.message
        })
        return;
      }
      let tableStatus = await this.changeBall();
      console.log(tableStatus, '====')
      if (tableStatus === undefined || tableStatus === 1) {
        wx.showToast({
          icon: 'none',
          title: '台子正在使用中'
        })
        return;
      };
      this.changeNextStage();
    }
    if (id === 2) {
      console.log(this.data.currentShop)
      post(APIS.payOrder, {
        uid: this.data.userInfo.id,
        // total_fee: info.deposit * 100,
        tab_id: this.data.info.id,
        type: this.data.type,
        name: 'deposit',
        shop: this.data.currentShop
      }).then(res => {
        const {
          wxpay,
          payment_id
        } = res.data;
        const that = this;
        wx.requestPayment({
          ...wxpay,
          success(res) {
            console.log(44444, res);
            that.setData({
              isShowHyTip: false
            });
            that.changeNextStage(1, payment_id);
          },
          fail(res) {
            console.log('err', res);
          }
        })
      });
    } else if (id == 3) {
      // 跳转other页面
      // wx.navigateTo({
      //   url: '/subPackagePay/pages/other',
      // })
      this.setData({
        isShowTip: false,
        isShowScan: true
      })
    } else if (id === 4) {
      this.setData({
        isShowTip: true
      });
    } else if (id === 5) {
      // 弹窗 敬请期待
      wx.showToast({
        icon: 'none',
        title: '敬请期待'
      })
    }
  },
  async getNuclear(url, type) {
    get(APIS.nuclear, {
      url,
      type
    }).then(res => {
      if (res.code === 0) {
        try {
          console.log(res);
          const obj = res.data[0].sku.title;
          const time = obj && obj.split('小时')[0].split('】')[1];
          const end = Date.now() + time * 60 * 60 * 1000;
          this.createOrder(0, -1, end);
        } catch (error) {

        }
      } else {
        // 弹窗
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
        return;
      }
    });
  },
  autoClose(time) {
    const { type, id } = this.data;
    const that = this;
    put(`${APIS.controll}`, {
      status: 0,
      id,
      type,
      // 是否添加order
      addOrder: 1,
      // 增加end时间戳
      end: Date.now() + time * 60 * 60 * 1000
    })
      .then(res => {
        if (res.code === 1) {
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
          return;
        }
        // 提示操作成功，并且返回
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
        this.createOrder(0, -1, 1);
      })
  },
  changeNextStage(is_deposit = 0, payment_id = -1) {
    console.log(121212121);
    this.createOrder(is_deposit, payment_id);
  },
  changeBall() {
    const url = this.data.type === 'ball' ? APIS.ball : APIS.card;
    return get(`${url}/${this.data.info.id}`)
      .then(res => {
        return res.data && res.data.status;
      })
  },
  createOrder(is_deposit = 0, payment_id, end = 0) {
    const {
      currentShop,
      currentShopName,
      coupon
    } = this.data;
    post(APIS.order, {
      shop: currentShop,
      table: this.data.info.number,
      sname: currentShopName,
      ltid: this.data.info.id,
      luid: this.data.userInfo.id,
      type: this.data.type,
      is_deposit,
      end,
      is_usequan: end > 0 ? 1 : 0,
      payment_id,
      coupon
    }).then((res) => {
      console.log(3333, res);
      if (res.code === 1) {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
        return;
      }
      const orderInfo = res.data;
      console.log(1111, orderInfo);
      try {
        this.setSystem();
        wx.navigateTo({
          url: `/subPackagePay/pages/task?ball=${this.data.info.id}&order=${orderInfo.id}&type=${this.data.type}`
        })
      } catch (error) {
        wx.navigateTo({
          url: `/subPackagePay/pages/task?ball=${this.data.info.id}&order=${orderInfo.id}&type=${this.data.type}`
        })
      }
    })
  },
  async setSystem() {
    // 开台成功,通知硬件
    const number = this.data.info.number;
    const key = this.data.type === 'ball' ? `b${number}` : 'c1';
    const bInfo = systemList.find(x => x.id === key) || {};
    const {
      mcuName,
      mcuid
    } = bInfo;
    console.log(key, mcuName, mcuid);
    await setBallSystem(mcuName, mcuid, 1);
    if (this.data.type === 'ball') {
      await setVoiceSystem(1, `A0${number}号桌开台成功`);
    }
  },
  handelPhone() {
    wx.makePhoneCall({
      phoneNumber: '19527270034'
    })
  },
  handleJumpToPay() {
    wx.navigateTo({
      url: '/subPackage/pages/pay'
    })
  },
  handleJumpToCoupon() {
    wx.navigateTo({
      url: '/subPackage/pages/coupon'
    })
  },
  // onShareAppMessage() {
  //   return getApp().globalData.shareMessage
  // }
})